
package fileby.ctrl.tabs;

import fileby.model.ISelectionManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;

/**
 *
 * @author Jacob
 */
public class TabContentListener extends MouseAdapter {

    private ISelectionManager selectionManager;
    private JPopupMenu popup;
    private boolean drag;
    private int latestMouseClick = MouseEvent.BUTTON1;

    public TabContentListener(JPopupMenu popup,
            ISelectionManager selectionManager) {

        this.popup = popup;
        this.selectionManager = selectionManager;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        drag = false;
        latestMouseClick = e.getButton();
        if (e.getButton() == MouseEvent.BUTTON1) {
            selectionManager.setAllSelected(false);
            ((JScrollPane)e.getSource()).grabFocus();
        } else if (e.getButton() == MouseEvent.BUTTON3) {
            showPopup(e);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if(!drag && latestMouseClick == MouseEvent.BUTTON1)
            selectionManager.setAllSelected(false);
        drag = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger())
            showPopup(e);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        drag = false;
        latestMouseClick = e.getButton();
        if (e.isPopupTrigger())
            showPopup(e);
    }

    private void showPopup(MouseEvent e) {
        if (!drag) {
            selectionManager.setAllSelected(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
    }


}
